package service

import (
	"shop/common/log"
	"shop/config"
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
	"shop/utils/genutil"
	"shop/utils/result"
	"shop/utils/sessionutil"
	"shop/utils/weixinutil"
	"time"
)

// LoginByWeixin 微信小程序授权登录
func LoginByWeixin(shopId int, weixinCode string) *result.Result {
	merchant := config.GetMerchantConfByShopId(shopId)
	if merchant == nil || merchant.ShopId == 0 {
		return result.Fail("商家不存在")
	}

	openid := weixinutil.GetWxMpOpenid(merchant.WxMpAppId, merchant.WxMpAppSecret, weixinCode)
	if openid == "" {
		return result.Fail("获取微信openid失败")
	}

	user := dao.GetUserByShopIdAndUsername(shopId, openid)
	if user == nil || user.Id == 0 {
		user = &entity.User{
			ShopId:   shopId,
			Username: openid,
		}
		if !registerUser(user) {
			return result.Fail("用户注册失败")
		}
	} else if user.Status != constant.UserStatusNormal {
		return result.Fail("账号异常，" + constant.UserStatusCN(user.Status))
	}
	go SetUserLoginTime(user.Id, time.Now().Unix())
	return result.Ok(sessionutil.SetUserSession(user))
}

func registerUser(user *entity.User) bool {
	user.Name = genutil.RandStr(4)
	user.Status = constant.UserStatusNormal
	user.CreateTime = time.Now().Unix()
	if err := dao.GetTx().Model(user).Create(user).Commit().Error; err != nil {
		log.Errorf("fail to crete user, err: %v", err)
		return false
	}
	log.Infof("auto register user, user: %v", user)
	return true
}
